package org.l.qiao.util;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 严秋旺 on 2015/8/8.
 */
public class JSONArrayConvert {

    /**
     * 将json列表格式的字符串转换为List对象
     *
     * @param source json列表格式的字符串,例：[1,false,3,"text"，{'key':'value'}]
     * @return List对象
     */
    public static List toList(String source) {
        JSONArray jsonArray = new JSONArray(source);
        return toList(jsonArray);
    }

    /**
     * 将JSONArray对象转换为List对象，子对象也将转换。若子对象为JSONObject类型，将会转换为Map对象
     *
     * @param jsonArray JsonArray对象
     * @return
     */
    public static List toList(JSONArray jsonArray) {
        List list = new ArrayList();
        int length = jsonArray.length();

        for (int i = 0; i < length; ++i) {
            Object object = jsonArray.opt(i);

            if(object == JSONObject.NULL){
                object = null;
            }else if (object instanceof JSONObject) {
                object = JSONConvert.toMap((JSONObject) object);
            } else if (object instanceof JSONArray) {
                object = JSONArrayConvert.toList((JSONArray) object);
            }

            list.add(object);
        }

        return list;
    }
}
